package com.xuexiang.xuidemo.app.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.fragment.app.Fragment;

import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.app.adapter.WordListItem;
import com.xuexiang.xuidemo.base.BaseFragment;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TestingVideo#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TestingVideo extends BaseFragment {

    private VideoView mVideoView;
    private String mVideoUrl;

    private static String ARG_PARAM1 = "videoUrl";

    public TestingVideo() {
        // Required empty public constructor
    }


    public static TestingVideo newInstance(String videoUrl) {
        TestingVideo fragment = new TestingVideo();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, videoUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mVideoUrl = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_testing_video;
    }

    @Override
    protected void initViews() {
        mVideoView = findViewById(R.id.video);
        initVideo();
    }

    private void initVideo() {
        if (TextUtils.isEmpty(mVideoUrl)) {
            Toast.makeText(getContext(), com.xuexiang.xui.R.string.xui_preview_video_path_error, Toast.LENGTH_SHORT).show();
            return;
        }
        Context self = getContext();
        mVideoView.setVideoPath(mVideoUrl);
        mVideoView.setOnErrorListener((mp, what, extra) -> {
            Toast.makeText(self, com.xuexiang.xui.R.string.xui_preview_play_failed, Toast.LENGTH_SHORT).show();
            return false;
        });
        mVideoView.start();
    }

    private void recycle() {
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && !mVideoView.isPlaying()) {
            mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            mVideoView.pause();
        }
    }

    @Override
    public void onStop() {
        if (isDetached() || isRemoving()) {
            recycle();
        }
        super.onStop();
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }
}